package org.catspaw.cherubim.persistence;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.catspaw.cherubim.persistence.ResourceCallback;

public abstract class DynamicProxyResourceMaster<R> implements ResourceMaster<R> {

	private R	entityManagerProxy;

	@SuppressWarnings("unchecked")
	public DynamicProxyResourceMaster(Class<? extends R> resourceClass) {
		entityManagerProxy = (R) Proxy.newProxyInstance(resourceClass.getClassLoader(), new Class[] { resourceClass },
														new ResourceInterceptor());
	}

	public R getResource() {
		return entityManagerProxy;
	}

	private class ResourceInterceptor implements InvocationHandler {

		public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
			return DynamicProxyResourceMaster.this.execute(new ResourceCallback<R, Object>() {

				public Object doInResource(R resource) {
					try {
						return method.invoke(resource, args);
					} catch (IllegalArgumentException e) {
						throw new IllegalStateException(e);
					} catch (IllegalAccessException e) {
						throw new IllegalStateException(e);
					} catch (InvocationTargetException e) {
						throw new IllegalStateException(e);
					}
				}
			});
		}
	}
}
